const $pub = require("../pub/pub"); //公共方法

module.exports = (io) => {
  let $methods = {
    //抽离方法
    _time: null,
    numClientsFn(roomName) {
      // 在线人数
      var clientsInRoom = io.sockets.adapter.rooms[roomName];
      var numClients = clientsInRoom
        ? Object.keys(clientsInRoom.sockets).length
        : 0;
      $pub.numClients = numClients;
      // console.log("房间：" + roomName + " ，当前有： " + numClients + " 用户");
      return numClients;
    },
    _setInterval(roomName, callBack) {
      //定时器
      let setNum = $pub.numClients;
      clearInterval(this._time);
      this._time = setInterval(() => {
        setNum = this.numClientsFn(roomName);
        callBack && callBack(setNum);
      }, 3000);
      this._time;
    },
  };
  // 客户端接入
  io.on("connection", (socket) => {
    // 接收客户端的消息
    socket.on("message", function (message) {
      console.log("推送 -> 接收到客户端发送信息的请求，消息内容： ", message);

      // for a real app, would be room-only (not broadcast)
      // socket.emit("message", message);
      socket.broadcast.emit("message", message);
    });

    console.log("有新用户接入，socket id：" + socket.id);

    // 接收客户端的消息
    socket.on("text", function (data) {
      io.sockets.in(data.roomName).emit("text", data);
    });

    // 创建或加入房间
    socket.on("create or join", function (room) {
      console.log("接收到客户端创建或加入房间的请求，房间名称： " + room);

      let numClients = $pub.numClients;
      // let numClients = $methods.numClientsFn(room)
      $methods._setInterval(room, (num) => {io.sockets.to(room).emit("numClients", num);});
      console.log("numClients:" + numClients);
      // 创建房间
      if (numClients == 0) {
        console.log("该用户 socket.id：" + socket.id + " 创建房间：" + room);

        socket.join(room);
        socket.emit("created", room, socket.id);
      }
      // 加入房间
      else if (numClients > 0) {
        console.log("该用户 socket.id：" + socket.id + " 加入房间：" + room);

        // 通知已在房间的用户有新用户要加入
        io.sockets.in(room).emit("join", room);

        // 通知该新用户加入成功
        socket.join(room);
        socket.emit("joined", room, socket.id);

        //已在房间的用户 新用户加入成功
        socket.broadcast.to(room).emit("ready", room);
      }
      // 房间满了
      else {
        socket.emit("full", room);
      }
    });
    socket.on("error", function (error) {
      console.log("error:" + error);
    });
  });
};
